import Layout from "./Layout";
import { Button, Form, Input, Spin, Result } from "antd";
import { useDispatch, useSelector } from 'react-redux'
import { signup, signup_reset } from "../../store/actions/signup";
import { Link } from 'react-router-dom'
import { useEffect } from "react";

export default function Signup() {
    const dispatch = useDispatch()
    const { loading, loaded, success, message } = useSelector(state => state.signup)

    const handleOnfinish = value => {
        dispatch(signup(value))
    }

    // 获取表单数据
    const [form] = Form.useForm()

    // 正在发送显示loading
    const showLoading = () => {
        if (loading) {
            return <Spin />
        }
    }

    // 表单提交成功 清空表单
    useEffect(() => {
        if (loaded && success) form.resetFields()
        // eslint-disable-next-line
    }, [loaded, success])

    // 注册成功显示提示信息
    const showSuccess = () => {
        if (loaded && success) {
            return (
                <Result status="success" title="注册成功" extra={[<Button type="primary" key="denglu"><Link to='/signin'>登录</Link></Button>]} />
            )
        }
    }

    // 离开界面重置
    useEffect(() => {
        return () => {
            dispatch(signup_reset())
        }
        // eslint-disable-next-line
    }, [])

    const showError = () => {
        if (loaded && !success) {
            return <Result status="warning" title="注册失败" subTitle={message} />
        }
    }

    const signupForm = () => {
        return (
            <Form form={form} onFinish={handleOnfinish}>
                <Form.Item label='昵称' name='name'>
                    <Input />
                </Form.Item>
                <Form.Item label='邮箱' name='email'>
                    <Input />
                </Form.Item>
                <Form.Item label='密码' name='password'>
                    <Input.Password />
                </Form.Item>
                <Form.Item>
                    <Button type='primary' htmlType='submit'>注册</Button>
                </Form.Item>
            </Form>
        )
    }
    return (
        <Layout title='注册' subTitle=''>
            {showLoading()}
            {showSuccess()}
            {showError()}
            {signupForm()}
        </Layout>
    )
}